package org.farm.product.domain.chain.handler;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.farm.common.response.enums.BusinessException;
import org.farm.common.response.enums.ResultCodeEnums;
import org.farm.product.domain.bo.ProductSpuBo;
import org.farm.product.domain.bo.ProductSpuExtensionBo;
import org.farm.product.domain.convert.ProductSpuExtensionBoConvert;
import org.farm.product.infra.basic.entity.ProductSpuExtension;
import org.farm.product.infra.basic.service.ProductSpuExtensionService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2025/4/23
 * @description
 */
@Slf4j
@Order(3)
@Component
public class ProductSpuExtensionHandler implements ProductSpuHandler {

    private final ProductSpuExtensionService productSpuExtensionService;

    private ProductSpuHandler nextHandler;

    public ProductSpuExtensionHandler(ProductSpuExtensionService productSpuExtensionService) {
        this.productSpuExtensionService = productSpuExtensionService;
    }

    @Override
    public void handler(ProductSpuBo productSpuBo) {
        ProductSpuExtensionBo productSpuExtensionBo = productSpuBo.getProductSpuExtension();
        if (Objects.isNull(productSpuExtensionBo)) {
            return;
        }
        ProductSpuExtension extension = ProductSpuExtensionBoConvert.INSTANCE.convertBoToEntity(productSpuExtensionBo);
        extension.setId(IdWorker.getId());
        extension.setSpuId(productSpuBo.getId());
        boolean save = productSpuExtensionService.save(extension);
        if (!save) {
            throw new BusinessException(ResultCodeEnums.BUSINESS_ERROR, "ProductSpuExtensionHandler save error");
        }
        log.info("ProductSpuExtensionHandler save success, spuId:{}, extension:{}", productSpuBo.getId(), extension);
        if (Objects.nonNull(nextHandler)) {
            nextHandler.handler(productSpuBo);
        }
    }

    @Override
    public void setNextHandler(ProductSpuHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    @Override
    public ProductSpuHandler getNextHandler() {
        return this.nextHandler;
    }
}
